package com.lalameow.serverlogingate.utiles;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cglib.beans.BeanCopier;

import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 陈刚
 * @version 1.0
 * @project guaranty.parent
 * @package com.haorui.commons.core.util
 * @createDate 2015/5/27 0027 12:06
 * @modfiyDate
 * @function
 */
public class BeanUtil {

    /**
     * 复制类source的属性到target
     * @param source
     * @param target
     */
    public static void beanCopy(Object source,Object target){
        BeanCopier.create(source.getClass(),target.getClass(),false).copy(source,target,null);
    }
    /**
     * 复制类source的属性到target(忽略为null的属性)
     * @param source
     * @param target
     */
    public static void beanCopyNotNull(Object source,Object target){
        BeanUtils.copyProperties(source,target,getNullPropertyNames(source));
    }

    /**
     * 获取为NULL的属性名称
     * @param source
     * @return
     */
    private static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }


    /**
     * 将实体类转换成任务表单
     * @param obj
     * @return
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     * @throws java.lang.reflect.InvocationTargetException
     */
    public static Map<String,Object> covObjetToMap(Object object){
        JSONObject obj=JSONObject.parseObject(JSONObject.toJSONString(object));
        Map<String,Object> resultVal=new HashMap<String, Object>();
        for (Map.Entry<String,Object> temp : obj.entrySet()) {
            if(temp.getKey()==null || temp.getValue()==null){
                continue;
            }
            resultVal.put(temp.getKey(),temp.getValue());
        }
        return resultVal;
    }


    public static Object convertValue(Class entityClass,String fieldName,Object value){
        try {
//
            String typeName=entityClass.getDeclaredField(fieldName).getType().getName();
            Class t= entityClass.getDeclaredField(fieldName).getType();
//            if(t.getSuperclass().getTypeName())
            if(t.getSuperclass().getTypeName().equals(Enum.class.getTypeName())){
                return Enum.valueOf(t,value.toString());
            }
            if(typeName.equals(Integer.class.getName())){
                return Integer.parseInt(value.toString());
            }else if(typeName.equals(Date.class.getName()) ){
                SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
                Date date = null;
                try {
                    date = dateFormat.parse(dateFormat.format(value));
                } catch (ParseException e) {
                    return value;
                }catch (Exception e){
                    try{
                        date = dateFormat.parse(value.toString());
                    }catch (Exception e1){
                        return null;
                    }

                }
                return date;
            }else if(typeName.equals(java.sql.Date.class.getName())){
                return java.sql.Date.valueOf(value.toString());
            }else if(typeName.equals(Long.class.getName())){
                return Long.parseLong(value.toString());
            }else if(typeName.equals(Short.class.getName())){
                return  Short.parseShort(value.toString());
            }else if(typeName.equals(Float.class.getName())){
                return Float.parseFloat(value.toString());
            }else if(typeName.equals(Double.class.getName())){
                return Double.parseDouble(value.toString());
            }else if(typeName.equals(BigDecimal.class.getName())){
                return BigDecimal.valueOf(Double.parseDouble(value.toString()));
            }else if(typeName.equals(Byte.class.getName())){
                return Byte.valueOf(value.toString());
            }else if(typeName.equals(Boolean.class.getName())){
                return Boolean.valueOf(value.toString());
            }else if(typeName.equals(Time.class.getName())){
                return Time.valueOf(value.toString());
            }else if(typeName.equals(Timestamp.class.getName())){
                return Timestamp.valueOf(value.toString());
            }else {
                return value;
            }
        } catch (Exception e) {
            //这里甚么都不要做！并且这里的异常必须这样写，不能抛出去。
            //如果这里的异常打印或者往外抛，则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
            return convertValue(entityClass.getSuperclass(),fieldName,value);
        }

    }


}
